package com.foton.websocket.controller;

import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author RenPu
 * @Date 2023/3/15 16:14
 * @Version 1.0
 * @Description: websocket对外暴露的接口编写格式
 **/

@Component
@ServerEndpoint(value = "/websocketApi/{id}")
public class WebSocketApi {

    //当前session对象
    private Session session;

    //储存Session的容器
    private static CopyOnWriteArraySet<Session> websokcetSet=new CopyOnWriteArraySet<>();

    @OnOpen //当有链接与后端链接，就会触发此方法
    public void getSeesion(Session session){
        this.session=session;
        websokcetSet.add(session);
        System.out.println("当前链接数量为："+websokcetSet.size());
        System.out.println("Session的唯一标识。可以进行精准推送，" +
                "例如将此值设置为用户的唯一标识，进行一些业务设计：：："+session.getId());
    }

    //接收前端页面，通过websocket发送的数据内容
    @OnMessage
    public void onMessage(String msg, Session session){
        System.out.println("接受到websocket的消息："+msg);
        sendMessage(msg,session);
    }

    //将通过前端接收的数据，进行业务处理推送给前端
    public void sendMessage(String msg,Session session){
        try {
            //获取websocket的Session对象
            //调用发送消息方法
            for (Session session1: websokcetSet){
                //推送消息排出当前的用户
                if(!session.equals(session1)){
                    session1.getBasicRemote().sendText(msg);

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
